package org.nimi317.web_gis.factory;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.core.toolkit.TableNameParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.ParameterMapping;
import org.nimi317.web_gis.context.SecurityContextHolder;
import org.nimi317.web_gis.utils.ListUtils;
import org.nimi317.web_gis.utils.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author thunderobot
 */
@Slf4j
public class RangeDivisionFactory extends BaseDivisionFactory {

    @Override
    public String divisionTableName(String name, String sql, TableNameParser.SqlToken sqlToken, PluginUtils.MPBoundSql boundSql) {
        String tableName = SecurityContextHolder.getTableName();
        if (StringUtils.isNotBlank(tableName) && tableName.contains(",")) {
            String param = sql.substring(sqlToken.getEnd());
            String query = sql.substring(0, sqlToken.getStart());
            StringBuilder builder = new StringBuilder();
            String[] split = tableName.split(",");
            List<ParameterMapping> mappings = boundSql.parameterMappings();
            List<ParameterMapping> result = new ArrayList<>();
            ListUtils.forHandle(Arrays.stream(split).toList(), s -> {
                builder.append(s);
                result.addAll(mappings);
            }, s ->
                    builder
                            .append(param)
                            .append(" union ")
                            .append(query));
            boundSql.parameterMappings(result);
            return builder.toString();
        }
        return tableName;
    }
}